<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page ref="searchSerSelect" label="serviceName" value="serviceNo" :select.sync="search.serviceNo" :url="website.searchLink.serviceUrl" placeholder-text="服务商" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page ref="searchOrgSelect" label="serviceName" value="serviceNo" :select.sync="search.orgNo" :url="website.searchLink.orgUrl" placeholder-text="机构" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{row}" slot="rptPayState">
        <div>
          <el-tag type="success" :color="rptPayStateType(row)" effect="dark">{{row.rptPayStateName}}</el-tag>
        </div>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button
          v-if="permissionList.viewBtn"
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleDetail(scope.row)"
          >审 核</el-button
        >
      </template>
      <template slot="menuRight">
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permissionList.exportBtn"
          @click="handleExport"
          >导出
        </el-button>
      </template>
    </avue-crud>
    <div class="curd-foter">
      <div class="redFontBox">总提现金额：<span class="redFont">{{ exhibition(countData.totalAmount) || 0}}</span> 元</div>
      <div class="redFontBox">总手续费：<span class="redFont">{{ exhibition(countData.totalFee) || 0 }}</span> 元</div>
      <div class="redFontBox">总服务费：<span class="redFont">{{ exhibition(countData.totalServiceFee) || 0 }}</span> 元</div>
      <div class="redFontBox">总到账金额：<span class="redFont">{{ exhibition(countData.totalIncomingAmount) || 0 }}</span> 元</div>
    </div>

    <!-- 新建 -->
    <el-dialog
      title="选择平台类型"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="selectType"
      v-if="selectType"
      :before-close="beforeCloseSelectType"
      v-loading="selectLoading"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
      width="610px"
    >
    <!-- 平台类型 -->
      <div class="wrapContainer">
        <div class="conWrap" v-for="(item,index) in selectList" :key="index" @click="selectTypeSubmit(item)">
          <span>平台类型：{{item.platformName}}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => { selectType = false }">取 消</el-button>
        <!-- <el-button type="primary" @click="selectTypeSubmit" >确 定</el-button> -->
      </span>
    </el-dialog>

  </basic-container>
</template>

<script>
import { getList,getExport,getListCount,getQueryPlatformList,changeForwardType } from "@/api/rb-oem/withdraw/withdraw";
import { mapGetters } from "vuex";
// import { dateFormat } from "@/util/date";
import { downloadFileExcel } from "@/util/util";
import selectPage from "@/components/select-page/select-page";

import Layout from '@/page/index/'
export default {
  props: {
    withdrawListType: {
      type: String,
      default: '0',
    },
  },
  components: {
    selectPage
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 110, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText:'重置',
        column: [
          {
            label: "提现编号",
            prop: "withdrawCode",
            type: "input",
            overHidden: true,
            minWidth:120,
            search: true
          },
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: 'select',
            addDisplay: false,
            editDisplay: false,
            search: true,
            span: 24,
            overHidden: true,
            width: 110,
            rules: [
              {
                required: true,
                message: "请选择服务商",
                trigger: "blur",
              },
            ],
          },
          {
            label: "服务商名称",
            prop: "serviceName",
            type: "input",
            overHidden: true,
            minWidth:180
          },
          {
            label: '',
            prop: 'isSelectChild',
            type: 'select',
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            searchType:"checkbox",
            searchLabelWidth: '0',
            dicData: [{
              label:'包含下级',
              value: 1
            }]
          },
          {
            label: "所属机构",
            prop: "orgNo",
            type: "select",
            dataType: "string",
            showColumn: false,
            search: true,
            filterable: true,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择所属机构",
                trigger: "blur",
              },
            ],
          },
          {
            label: "提现金额",
            prop: "rowMoney",
            type: "input",
            overHidden: true,
            minWidth:82
          },
          {
            label: "提现状态",
            prop: "rowStatusName",
            type: "input",
            overHidden: true,
            minWidth:82
          },
          {
            label: "提现手续费",
            prop: "localFee",
            type: "input",
            overHidden: true,
            minWidth:95
          },
          {
            label: "服务费率",
            prop: "rowProfitScale",
            type: "input",
            overHidden: true,
            minWidth:95
          },
          {
            label: "服务费",
            prop: "rowProfitNum",
            type: "input",
            overHidden: true,
            minWidth:95
          },
          {
            label: "实际到账金额",
            prop: "incomingAmount",
            type: "input",
            overHidden: true,
            minWidth:95
          },
          {
            label: "账户类型",
            prop: "accountTypeName",
            type: "input",
            overHidden: true,
            minWidth:82
          },
          {
            label: "转账类型",
            prop: "forwardTypeName",
            type: "input",
            overHidden: true,
            minWidth:82
          },
          {
            label: "账户类型",
            prop: "accountType",
            type: "select",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=account_type",
            formslot:true,
            overHidden:true,
            hide: true,
            display: false
          },
          {
            label: "转账类型",
            prop: "forwardType",
            type: "select",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=forward_type",
            formslot:true,
            overHidden:true,
            hide: true,
            display: false
          },
          {
            label: "开户名称",
            prop: "robBankName",
            type: "input",
            search: true,
            overHidden: true,
            minWidth:220
          },
          {
            label: "开户支行",
            prop: "robBankBranch",
            type: "input",
            // search: true,
            overHidden: true,
            minWidth:180
          },
          {
            label: "联行号",
            prop: "robUnionNumber",
            type: "input",
            // search: true,
            overHidden: true,
            minWidth:82
          },
          {
            label: "银行账号",
            prop: "robBankNo",
            type: "input",
            search: true,
            overHidden: true,
            minWidth:150
          },
          // {
          //   label: "回款状态",
          //   prop: "backStateName",
          //   type: "input",
          //   // search: true,
          //   overHidden: true,
          //   minWidth:82
          // },
          {
            label: "提现时间",
            prop: "withdrawDate",
            type: "select",
            // sortable: true,
            overHidden:true,
            minWidth: 140,
          },
          // {
          //   label: "审核时间",
          //   prop: "adminDate",
          //   type: "select",
          //   // sortable: true,
          //   overHidden:true,
          //   minWidth: 140,
          // },
          // {
          //   label: "到款时间",
          //   prop: "notifyDate",
          //   type: "select",
          //   // sortable: true,
          //   overHidden:true,
          //   minWidth: 140,
          // },

          {
            label: "提现备注",
            prop: "rowRemarks",
            type: "input",
            // search: true,
            overHidden: true,
            minWidth:200
          },
          // {
          //   label: "驳回理由",
          //   prop: "robReason",
          //   type: "input",
          //   // search: true,
          //   overHidden: true,
          //   minWidth:200
          // },
          // {
          //   label: "交易状态",
          //   prop: "rptPayState",
          //   type: "select",
          //   dataType: "number",
          //   props: {
          //     label: "dictValue",
          //     value: "dictKey"
          //   },
          //   search: true,
          //   ////sortable: true,
          //   dicUrl: "/api/blade-system/dict/dictionary?code=rpt_pay_state",
          //   formslot:true,
          //   overHidden:true,
          //   minWidth: 92,
          //   searchOrder: 1
          // },
          
          {
            label: "提现时间段",
            prop: "adminDateTime",
            type: "datetimerange",
            searchRange: true,
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd HH:mm:ss',
            valueFormat:'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: "提现开始时间",
            endPlaceholder: "提现结束时间",
            search: true,
            rules: [
              {
                required: true,
                message: "请选择提现时间段",
                trigger: "blur",
              },
            ],
            hide: true,
            display: false,
            searchSpan: 12
          }
          // {
          //   label: "审核时间段",
          //   prop: "withdrawDateTime",
          //   type: "datetimerange",
          //   searchRange: true,
          //   defaultTime:['00:00:00', '23:59:59'],
          //   format:'yyyy-MM-dd HH:mm:ss',
          //   valueFormat:'yyyy-MM-dd HH:mm:ss',
          //   startPlaceholder: "审核开始时间",
          //   endPlaceholder: "审核结束时间",
          //   search: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择审核时间段",
          //       trigger: "blur",
          //     },
          //   ],
          //   hide: true,
          //   display: false,
          //   searchSpan: 12
          // }
        ]
      },
      data: [],
      countData: {},
      currentIndex:0,
      selectType:false,
      selectRow:{},
      selectList:[],
      selectLoading:false
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.oem_withdraw_view, false),
        exportBtn: this.vaildData(this.permission.oem_withdraw_export, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    // 交易状态
    rptPayStateType() {
      return (row) => {
        if(row.rptPayState==0){
          return '#E6A23C' //未支付
        }else if(row.rptPayState==1&&row.rptIsRefund!==0){
          return '#6463bf' //支付成功（已退款）
        }else if(row.rptPayState==1){
          return '#67C23A' //支付成功
        }else if(row.rptPayState==2){
          return '#909399'    //支付失败
        }else if(row.rptPayState==3){
          return '#909399' //取消支付
        }else if(row.rptPayState==4){
          return '#909399' //退款中
        }else if(row.rptPayState==5){
          return '#2fdeebf2' //已退款
        }else if(row.rptPayState==6){
          return '#909399' //退款失败
        }else{
          return '#909399' 
        }
      };
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  watch: {
    "search.adminDateTime"(val){
      if(val){
        this.search.beginAdminDate = val[0];
        this.search.endAdminDate = val[1];
      }else{
        this.search.beginAdminDate = "";
        this.search.endAdminDate = "";
      }
    }
  },
  methods: {
    // 选择类型 确定
    selectTypeSubmit(item){
      let that = this;
      that.selectLoading = true
      let param ={
        id:that.selectRow.id,
        forwardType:item.id
      }
      changeForwardType(param).then(() =>{
        // that.$message({ type: "success", message: res.data.msg });
        that.selectLoading = false;
        that.selectType = false

        let objItem = Buffer.from(JSON.stringify({
        processId:that.selectRow.id,
        taskId:that.selectRow.taskId,
        processInsId:that.selectRow.processInsId
        })).toString('base64');
        this.$router.addRoutes([{
          path: `/workflow/process/external`,
          component: Layout,
          children: [{
            path: 'withdrawAudit/detail',
            name: '提现审核',
            component: () => import(`@/views/plugin/workflow/process/external/withdrawAudit/detail.vue`)
          }]
        }])
        this.$router.push(`/workflow/process/external/withdrawAudit/detail?p=${objItem}`)
      }).catch(() => {
        that.selectLoading = false;     
      });

    },
    handleDetail(row) {
      let that = this;
        that.selectRow = row;

      if(row.accountType === 1){
        that.selectLoading = true;
        getQueryPlatformList({}).then(res=>{
          that.selectList = res.data.data.list
          that.selectLoading = false
          if(that.selectList.length === 1){
            that.selectTypeSubmit(that.selectList[0])
          } else if(that.selectList.length < 1){
            that.$message({ type: "warn", message: '暂无平台类型' });
          } else {
            that.selectType = true;
          }
        })
      }else{
        let objItem = Buffer.from(JSON.stringify({
        processId:that.selectRow.id,
        taskId:that.selectRow.taskId,
        processInsId:that.selectRow.processInsId
        })).toString('base64');

        this.$router.addRoutes([{
          path: `/workflow/process/external`,
          component: Layout,
          children: [{
            path: 'withdrawAudit/detail',
            name: '提现审核',
            component: () => import(`@/views/plugin/workflow/process/external/withdrawAudit/detail.vue`)
          }]
        }])
        this.$router.push(`/workflow/process/external/withdrawAudit/detail?p=${objItem}`)
      }
    },
    // 点击状态
    currentClick(index){
      this.currentIndex = index;
    },
    /**
     * @func edit,view 打开之前回调
     * @desc 点击获取点击天数时间
     * */
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {};
      this.search = {};
      this.$set(this.search, 'adminDateTime', ["",""]);
      // this.$set(this.search, 'withdrawDateTime', ["",""]);
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;

      params.withdrawListType = this.withdrawListType;

      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      /**
       * @func 统计
       * @desc 根据条件获取统计
       * */
      getListCount(Object.assign(params, this.query)).then((res) => {
        this.countData = res.data.data;
      });
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
    handleExport() {
      // if (this.search.adminDateTime[0]) {
      //   this.search.beginAdminDate = this.search.adminDateTime[0];
      // }
      // if (this.search.adminDateTime[1]) {
      //   this.search.endAdminDate = this.search.adminDateTime[1];
      // }
     
      let params ={
        ...this.search,
        current:'-1',
        size:'-1',
        withdrawListType:this.withdrawListType
      }
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        getExport(params).then((res) => {
          downloadFileExcel(res);
        },(error) => {
            window.console.log(error);
          }
        );
      })
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  },
  created(){
    this.$root.Bus.$on('Examine',()=>{
      this.onLoad(this.page);
    }) 
  },
  // 在销毁组件之前 销毁监听
  beforeDestroy(){
    this.$root.Bus.$off('Examine')
  }
};
</script>

<style lang="scss" scoped>
.wrapContainer{
  height: 200px;
  display: flex;
  justify-content: flex-start;
  align-content: flex-start;
  flex-wrap: wrap;
  overflow-y: scroll;
}
.conWrap{
  width: 260px;
  background: #fff;
  border-radius: 10px;
  padding: 10px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border: 1px solid rgba(0, 102, 255, 0.08);
  -webkit-box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.05);
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.05);
  cursor: pointer;
  display: flex;
  align-items: center;
  margin: 0 20px 20px 0px;
}

.conWrap:hover{
  background: rgba(2, 86, 255, 0.1);
}


/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}

.btnColor{
  background: #409EFF;
  color: #fff;
}

.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;

  .redFontBox {
    margin-right: 40px;
    .redFont {
      color: red;
    }
  }
}

/deep/ .avue-crud__pagination{
  padding-bottom: 0 !important;
}



</style>